<template>
  <div>
    <BusinessTable
      ref="businessTable"
      :search-params="searchParams"
      :table-columns="tableColumns"
      :page-query-url="pageQueryUrl"
      :custom-btn="customBtn"
      @custom-btn="customBtnClick"
    />
    <a-drawer title="流程查看" width="80%" :visible="showDataDrawer" :body-style="{ paddingBottom: '80px' }" :destroyOnClose="true" @close="closeDataDrawer">
      <FlowDesign ref="FlowDesign" :node="nodeData" :readable="true" :readable2="showDataDrawer" @cancel="closeDataDrawer" />
    </a-drawer>
    <a-drawer title="流程调试" width="800px" :visible="debugDrawer" :body-style="{ paddingBottom: '80px' }" :destroyOnClose="true" @close="closeDebugDrawer">
      <a-form-model :model="debugForm" :rules="rules" ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="流程模型" prop="processCode">
          <a-select v-model="debugForm.processCode" placeholder="请输入流程编号" show-search option-filter-prop="children" :filter-option="filterOption" :showArrow="false">
            <a-select-option :value="item.code" v-for="(item, index) in processSource" :key="index">
              {{ item.name + '(' + item.code + ')' }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="流程标题" prop="processTitle">
          <a-input v-model="debugForm.processTitle" placeholder="请输入流程标题"></a-input>
        </a-form-model-item>
        <a-form-model-item label="发起人" prop="processCreator">
          <a-input v-model="debugForm.processCreator" placeholder="请输入流程发起人账号，例如：yc90092989"></a-input>
        </a-form-model-item>
        <a-form-model-item label="下个环节审批人" prop="nextAssignee">
          <a-input v-model="debugForm.nextAssignee" placeholder="请输入下个环节审批人账号，例如：yc90092989"></a-input>
        </a-form-model-item>
        <a-form-model-item label="业务数据（JSON）" prop="businessData">
          <a-textarea :placeholder="businessDataTip" allow-clear v-model="debugForm.businessData" :autoSize="{ minRows: 2 }" />
        </a-form-model-item>
      </a-form-model>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button :style="{ marginRight: '10px' }" type="primary" @click="createProcess">
          提交
        </a-button>
        <a-button @click="closeDebugDrawer">取消</a-button>
      </div>
    </a-drawer>
  </div>
</template>

<script>
  import BusinessTable from '@/components/BusinessTable';
  import { CUSTOM_BTN, SEARCH_PARAMS } from '@/views/instance/index';
  export default {
    name: 'instance',
    components: { BusinessTable },
    data() {
      return {
        rules: {
          processCode: [{ required: true, message: '流程编码不能为空', trigger: ['change', 'blur'] }],
          processTitle: [{ required: true, message: '流程标题不能为空', trigger: ['change', 'blur'] }],
          processCreator: [{ required: true, message: '流程发起人不能为空', trigger: ['change', 'blur'] }],
          businessData: [{ required: true, message: '业务数据（JSON）不能为空', trigger: ['change', 'blur'] }],
        },
        businessDataTip:
          '{\n' +
          '  "leaveType": "年休假",\n' +
          '  "startTime": "2025-02-18 08:30:12",\n' +
          '  "endTime": "2025-02-18 08:30:12",\n' +
          '  "dayCount": 1,\n' +
          '  "reason": "我就是想请假"\n' +
          '}',
        processSource: [],
        debugForm: {
          processCode: null,
          processTitle: null,
          processCreator: null,
          nextAssignee: null,
          businessData: null,
        },
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
        debugDrawer: false,
        searchParams: SEARCH_PARAMS,
        tableColumns: [
          {
            title: '流程主题',
            dataIndex: 'processTitle',
            key: 'processTitle',
          },
          {
            title: '当前处理人',
            dataIndex: 'assignee',
            key: 'assignee',
          },
          {
            title: '当前环节',
            dataIndex: 'activityName',
            key: 'activityName',
          },
          {
            title: '流程状态',
            dataIndex: 'status',
            key: 'status',
          },
          {
            title: '流程编号',
            dataIndex: 'processCode',
            key: 'processCode',
          },
          {
            title: '流程版本',
            dataIndex: 'processVersion',
            key: 'processVersion',
          },
          {
            title: '流程图',
            dataIndex: 'action',
            customRender: (text, record, index) => {
              return (
                <span class="action-col">
                  <a onClick={() => this.actionClick(record, index)}>查看</a>
                </span>
              );
            },
            slots: { title: 'action' },
          },
          {
            title: '创建人',
            dataIndex: 'createdBy',
            key: 'createdBy',
          },
          {
            title: '创建日期',
            dataIndex: 'creationDate',
            key: 'creationDate',
          },
          {
            title: '修改人',
            dataIndex: 'lastUpdatedBy',
            key: 'lastUpdatedBy',
          },
          {
            title: '修改日期',
            dataIndex: 'lastUpdateDate',
            key: 'lastUpdateDate',
          },
        ],
        pageQueryUrl: this.api.process.pageQueryProcess,
        customBtn: CUSTOM_BTN,
        nodeData: null,
        showDataDrawer: false,
      };
    },
    created() {
      this.queryAllProcess();
    },
    methods: {
      queryAllProcess() {
        this.axios.get(this.api.process.queryAllProcess).then((res) => {
          this.processSource = res.data;
        });
      },
      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
      },

      createProcess() {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.axios
              .get(this.api.process.queryProcessDetail, {
                params: {
                  processCode: this.debugForm.processCode,
                },
              })
              .then((res) => {
                if (res.code === 'ok') {
                  const processInfo = { ...res.data.processInfo, processTitle: this.debugForm.processTitle };
                  const businessData = JSON.parse(this.debugForm.businessData);
                  const body = {
                    action: 'create',
                    comment: '流程调试',
                    nextAssignee: this.debugForm.nextAssignee,
                    processInfo: processInfo,
                    businessData: businessData,
                  };
                  this.axios.post(this.api.process.operateProcess, body).then((res1) => {
                    if (res1.code === 'ok') {
                      this.$message.success('创建流程成功');
                      this.debugDrawer = false;
                      this.$refs.businessTable.reset();
                    }
                  });
                }
              });
          }
        });
      },
      closeDataDrawer() {
        this.showDataDrawer = false;
      },
      closeDebugDrawer() {
        this.debugDrawer = false;
      },
      actionClick(record, index) {
        console.log(index);
        console.log(record);
        //查询流程数据
        this.axios
          .get(this.api.process.queryProcessDefinition, {
            params: {
              instanceId: record.id,
            },
          })
          .then((res) => {
            this.nodeData = res.data;
            this.showDataDrawer = true;
          });
      },
      customBtnClick(code) {
        const func = this[code];
        func();
      },
      debug() {
        this.debugDrawer = true;
      },
      route() {
        if (this.$refs.businessTable.selectedRowKeys.length === 0) {
          this.$message.warn('请至少选择一行数据');
          return;
        }
        if (this.$refs.businessTable.selectedRowKeys.length > 1) {
          this.$message.warn('只能选择一行数据');
          return;
        }
        const index = this.$refs.businessTable.selectedRowKeys[0];
        const data = this.$refs.businessTable.tableData[index];
        console.log(data);
      },
      cancel() {
        if (this.$refs.businessTable.selectedRowKeys.length === 0) {
          this.$message.warn('请至少选择一行数据');
          return;
        }
        alert('cancel');
      },
      delete() {
        if (this.$refs.businessTable.selectedRowKeys.length === 0) {
          this.$message.warn('请至少选择一行数据');
          return;
        }
        alert('delete');
      },
    },
  };
</script>

<style scoped></style>
